(function(factory) {
	if (typeof define === "function" && define.amd) {
		// AMD. Register as an anonymous module.
		define(['HteOS/tile/Clock','HteOS/tile/Music','HteOS/tile/News','HteOS/tile/Stock','HteOS/tile/Weather'],factory);
	} else {
		// Browser globals
		factory();
	}
}(function() {
	/**
	 * @author 李球 <service@hteos.com>
	 * @class HteOS.metro.Tile 磁贴组件
	 * @singleton
	 */
	var Tile = HteOS.metro.Tile = function(app){
		this.app = app;
		this.size = app.size;
		this.render();
	}
	
	Tile.prototype.setSize = function(size){
		var el = this.el;
		el.removeClass("hte-tile-" + this.size);
		el.addClass("hte-tile-" + size);
		this.size = size;
		HteOS.TileManager.stop(this);
		el.html("");
		this.injectContent();
		HteOS.TileManager.start(this);
	};
	
	/**
	 * 渲染应用对应的DOM，如果定义了toggle，HteOS.TileManager将会根据配置的动态类开启动态磁贴
	 */
	Tile.prototype.render = function() {
		if(this.rendered === true){
			return this.el;
		}
		var me = this,animate = me.animate;
		var tpl,el;
		//background-color:<%=bgcolor%>;
		tpl = HteOS.Template.compile("<div class=\"hte-tile hte-tile-<%=size%>\""
				+ "style=\"color:<%=color%>;\" data-app-id=\"<%=id%>\"></div>");
		el = $(tpl(me.app));
		//el.data('appId', me.app.id);
		this.el = el;
		if(this.app.hidden){
			el.addClass("hte-tile-hidden");
		}
		this.tplComplieSuccess = false;
		if(this.app.tpl){
			try{
				this.tpl = HteOS.Template.compile(this.app.tpl);
				this.tplComplieSuccess = true;
			}catch(e){
				console.error("Compile template of " + this.app.name + " error");
				console.log(e);
				tplComplieSuccess = false;
			}
		}
		this.injectContent();
		this.draggable();
		this.droppable();
		me.rendered = true;
		//启动自定义磁贴
		HteOS.TileManager.start(this);
		return el;
	};
	
/**
	 * @private
	 * 通过配置的属性来注入内容
	 * <p>通过模板渲染，模板使用的组件是<a href="">artTemplate</a></p>
	 * <ul>
	 *	<li>直接渲染，使用配置好的静态内容直接渲染</li>
	 * 	<li>远程加载，加载远程数据，并根据配置渲染  HteOS.app.App.load</li>
	 * 	<li>模板渲染，根据配置的模板内容渲染</li>
	 * 	<li>如果没有设置动态磁贴的内容则使用默认的ui渲染</li>
	* </ul>
	 */
	Tile.prototype.injectContent = function(){
		var me = this,el = me.el,app = this.app;
		if(app.html && app.renderer == "plain"){
			el.html(app.html);
		}else if(app.url){
			this.load();
		}else if(app.renderer == 'template'){
			if(this.tplComplieSuccess ){
				el.html(this.tpl(app));
			}else{
				el.append($("<div class=\"hte-tile-text\">模板编译失败，无法渲染</div>"));
			}
		}else{
			var tpl = this.getTpl();
			el.html(tpl(app));
		}
	};
	
	/**
	 * @private
	 * 加载动态磁贴，根据App配置的url异步获取数据，并根据配置好的渲染方式进行渲染
	 * <ul>
	 *	<li>直接渲染，使用获取到的静态内容直接渲染</li>
	 * 	<li>模板渲染，根据配置好的模块渲染获取的远程数据</li>
	 * </ul>
	 */
	Tile.prototype.load = function(){
		var me = this,renderer = this.app.renderer,el = me.getEl(),app = this.app;
		HteOS.Masker.mask(el,"正在加载...");
		if(!this.tplComplieSuccess && renderer == 'template'){
			this.getEl().append($("<div class=\"hte-tile-text\">模板编译出错，无法渲染</div>"));
			return ;
		}
		$.ajax({
			url : this.url,
			dataType : renderer == 'plain' ? 'html' : 'json',
			success : function(data){
				HteOS.Masker.unmask();
				if(me.renderer == 'plain'){
					me.getEl().html(data);
				}else{
					if(Object.prototype.toString.call(data) == "[object Object]"){
						data.name = app.name;
						data.icon = app.icon;
						data.image = app.image;
					}
					me.getEl().html(me.tpl(data));
				}
			},
			error : function(){
				HteOS.Masker.mask(el,"加载失败");
			}
		});
	};
	
	 /**
	 * 设置磁贴拖拽放下的方式
	 */
	Tile.prototype.droppable = function() {
			var me = this,app = this.app;
			me.el.droppable({
				accept: ".hte-tile",
				over: function(event, ui) {
					var sapp = HteOS.AppManager.getByEl($(ui.draggable.get(0)));
					var tile = HteOS.metro.View.getTile(sapp.id);
					sapp.dropTargetGroup = app.getGroup();
					var index = app.indexOf(),index2 = sapp.indexOf();
					var source = tile.ghost,offset2 = source.offset();
					var target = $(this), offset1 = target.offset();
					var plus = false;
					if(offset2.top > offset1.top){
						source.insertAfter(target);
						plus = true;
					}
					else if(offset1.top = offset2.top){
						if(offset1.left > offset2.left){
							source.insertAfter(target);
							plus = true;
						}else{
							source.insertBefore(target);
						}
					}else{
						source.insertBefore(target);
					}
					if(sapp.getGroup() != app.getGroup() && index2 < index && plus === true){
						index ++;
					}
					sapp.dropIndex = index;
				}
		});
	};
	
	/**
	 * 启动磁贴拖拽
	 */
	Tile.prototype.draggable = function(element) {
		var me = this,metro = HteOS.Metro,
			$el = metro.getEl();
		var dd = this;
		this.el.draggable({
			containment: $(".hte-metro-container"),
			scroll : true,
			revert : false,
			helper:function(){
				var source = $(this).clone();
				source.addClass("hte-tile-dd-proxy");
				source.css("z-index", 10);
				source.html("");
				source.css("background-color",me.app.bgcolor);
				source.appendTo($el);
				return source;
			},
			start: function(event, ui) {
				$el.addClass("hte-metro-dragging");
				var tile = $(this);
				tile.hide();
				me.ghost = tile.clone();
				me.ghost.addClass("hte-tile-ghost");
				me.ghost.html("");
				me.ghost.css("visibility", "hidden");
				me.ghost.show();
				me.ghost.insertBefore(tile);
				//ui.draggable.dragSource = app;
			},
			stop: function(event, ui) {
				var tile = $(this)
				$el.removeClass("hte-metro-dragging");
				tile.show();
				me.ghost.remove();
				if(me.app.dropTargetGroup){
					me.app.dropTargetGroup.insert(me.app,me.app.dropIndex);
					me.app.dropTargetGroup = null;
					me.app.dropIndex = null;
				}
			}
		});
	};

	Tile.prototype.destroy = function(){
		this.app = null;
		this.el.remove();
		this.el = null;
	};
	
	/**
	 * 将隐藏的应用对应的磁贴显示出来
	 * */
	Tile.prototype.show = function(){
		this.getEl().removeClass("hte-tile-hidden");
	};
	
	/**
	 * 隐藏应用对应的磁贴
	 * */
	Tile.prototype.hide = function(){
		this.getEl().addClass("hte-tile-hidden");
	};
	
	Tile.prototype.getEl = function(){
		return this.el;
	};
	
	/**
	 * @property
	 * 磁贴的预设模板
	 */
	Tile.prototype.tpls = {
		
		1: HteOS.Template.compile( 
				 "<div class=\"hte-tile-content hte-tile-outline\" style=\"background-color:<%=bgcolor%>\">"
					 +"<div class=\"hte-tile-icon\">"
						+ "<img src=\"<%=icon%>\">" 
					+ "</div>" 
					+ "<div class=\"hte-tile-name\"><%=name%></div>"+
				"</div>"),
			
		2: HteOS.Template.compile(
				"<div class=\"hte-tile-content hte-tile-outline\" style=\"background-color:<%=bgcolor%>\">"
					+"<img class=\"hte-tile-wallpaper-image\" src=\"<%=image%>\">" 
					+ "<div class=\"hte-tile-name\"><%=name%></div>"
				+"</div>")
	};

	/**
	 * 根据UI获得相对应的模板函数
	 * @return {Function} tpl
	 */
	Tile.prototype.getTpl = function() {
		return this.tpls[this.app.ui] || this.tpls[1];
	};

}));
